package utils

import (
	"fmt"
	"github.com/go-resty/resty/v2"
	"net/http"
	"time"
)

var client = resty.New()

func init() {
	// 设置连接池参数
	client.SetTransport(&http.Transport{
		MaxIdleConns:        100,              // 设置最大空闲连接数
		MaxIdleConnsPerHost: 20,               // 设置每个主机的最大空闲连接数
		IdleConnTimeout:     30 * time.Second, // 设置空闲连接超时时间
	})
	client.SetDisableWarn(true)
	client.SetTimeout(20 * time.Second)             // 设置超时时间
	client.SetRetryCount(3)                         // 设置重试次数
	client.SetRetryWaitTime(500 * time.Millisecond) // 设置重试等待时间
}
func GetClient() *resty.Client {
	return client
}
func EsDocExists(host, indexName, _id string) bool {
	url := fmt.Sprintf("%s/%s/_doc/%s", host, indexName, _id)
	response, err := client.SetBasicAuth("elastic", "qqqAAA0130").NewRequest().Head(url)
	if err != nil {
		return false
	}
	return response.StatusCode() == 200
}
func EsCreateDoc(body map[string]any, host, indexName, _id string) (*resty.Response, error) {
	url := fmt.Sprintf("%s/%s/_doc/%s", host, indexName, _id)
	return client.NewRequest().SetBasicAuth("elastic", "qqqAAA0130").SetHeader("content-type", "application/json").SetBody(body).Post(url)
}
